<template>
  <basic-dialog :visible="isVisible"
                :title="`车间设备排序`"
                isShowBasicFooter
                :min-width="'600px'"
                :max-height="'800px'"
                :isShowInnerLoading="isShowInnerLoading"
                @close="isVisible = false"
                @submit="submit()"
  >
      <div class="padding-20 padding-b-0">
        <div class="q-mb-md">此排序适用于所有模块</div>
        <div class="flex">
          <div style="width: 285px" class="flex">
            <yz-input
              class="q-mr-sm"
              v-model="dragType"
              inputType="select"
              :options="dragOptions"
              @input="onChangeDragType"
              title="排序方式"
            />
            <q-icon name="iconfont icontubiao-72" class="font-16 cursor-pointer" style="margin-top: 7px">
              <q-tooltip>“按组织排序”指设备排序=生产组织排序+组织内设备自定义排序；“按设备排序”指设备排序=车间内设备自定义排序</q-tooltip>
            </q-icon>
          </div>
          <div style="width: 260px" v-if="dragType === 1">
            <yz-input
              class="margin-r-20"
              v-model="workshop"
              inputType="select"
              :options="workshopOptions"
              @input="onChangeWorkShop"
              title="车间"
            />
          </div>
        </div>

        <!--   按组织排序     -->
        <div class="flex justify-between" v-if="dragType === 2">
            <div class="drag-one">
              <div class="drag-one-header">生产组织
                <q-icon name="iconfont icontubiao-72" class="font-16 cursor-pointer">
                  <q-tooltip>可对同层级且属于同一个上级的生产组织拖拽排序</q-tooltip>
                </q-icon>
              </div>
              <div class="scrollbar drag-one-main">
                      <div
                              v-for="element in simple"
                              :key="element.schemaId"
                      >
                          <drag-tree-item :treeData="element" @onSelDevice="onSelDevice" :value="simpleId" :key="element.schemaId"/>
                      </div>
              </div>
            </div>
            <div class="drag-two">
              <div class="drag-two-header">设备列表
                <q-icon name="iconfont icontubiao-72" class="font-16 cursor-pointer" style="color: rgba(0, 0, 0, 0.65);">
                  <q-tooltip>同一生产组织下的设备支持拖拽排序</q-tooltip>
                </q-icon>
              </div>
              <div class="scrollbar drag-two-main">
                <div v-for="(v, i) in deviceSchemeListClone" :key="i">
                  <draggable
                      tag="div"
                      v-model="deviceSchemeListClone[i]"
                      v-bind="{
                      animation: 200,
                      group: deviceSchemeListClone[i],
                      disabled: false,
                      ghostClass: 'ghost'
                  }"
                  >
                    <div v-for="(item) in v" :key="item.id" class="drag-two-main-item"
                    >{{item.deviceName}}
                      <q-tooltip>{{item.deviceName}}</q-tooltip>
                    </div>
                  </draggable>
                </div>
              </div>
            </div>
        </div>
        <!--   按设备排序     -->
        <draggable
          v-else
          class="list-group"
          tag="ul"
          v-model="deviceList"
          v-bind="{
          animation: 200,
          group: 'description',
          disabled: false,
          ghostClass: 'ghost'
        }"
        >
          <li
            class="list-group-item"
            v-for="element in deviceList"
            :key="element.id"
          >
            <div class="flex-1 ellipsis">设备：{{ element.deviceName }}({{element.deviceNumber}})</div>
            <div class="flex-1 ellipsis">产线： {{ element.lineName || '-' }}</div>
          </li>
        </draggable>
      </div>
  </basic-dialog>
</template>
<script>
import _ from 'lodash'
import consuming from '../../boot/plan/process-time-consuming'
import Draggable from 'vuedraggable'
import { getDeviceBySchema, getDeviceByWorkshopId, setDeviceBySchema } from '../../boot/tpm/equipment-record'
import { getSchemaOrder, setSchemaOrder } from '../../boot/program-v2/machine'
import DragTreeItem from './drag-tree-item.vue'

export default {
  name: 'change-device-dialog',
  components: {
    DragTreeItem,
    Draggable
  },
  props: {
  },
  data () {
    return {
      isVisible: false,
      isShowInnerLoading: false,
      workshop: '',
      dragType: 1,
      workshopOptions: [],
      dragOptions: [ {
        label: '按设备排序',
        value: 1
      }, {
        label: '按组织排序',
        value: 2
      }],
      deviceList: [],
      deviceSchemeList: [], // 组织排序的设备
      deviceSchemeListClone: [], // 组织排序的设备
      simple: [],
      simpleId: '',
      allSchemasData: []
    }
  },
  computed: {

  },
  watch: {

  },
  mounted () {
  },
  methods: {
    handleDragStart () {
      this.deviceSchemeListClone = _.cloneDeep(this.deviceSchemeList)
    },
    handleDragEnd (event) {
      const oldItem = this.deviceSchemeListClone[event.oldIndex]
      const newItem = this.deviceSchemeListClone[event.newIndex]
      if (oldItem.workshopId === newItem.workshopId && newItem.lineId !== oldItem.lineId) {
        const originalIndex = event.oldIndex
        this.deviceSchemeList.splice(originalIndex, 0, this.deviceSchemeList.splice(event.newIndex, 1)[0])
        this.deviceSchemeListClone = _.cloneDeep(this.deviceSchemeList)
      }
    },
    onSelDevice (val) {
      this.simpleId = val.schemaId
      this.setDeviceBySchema()
      this.getDeviceBySchema(val)
    },
    async setDeviceBySchema () {
      this.deviceSchemeList = this.deviceSchemeListClone.flat()
      const list = this.dragType === 2 ? this.deviceSchemeList : this.deviceList
      if (_.isEmpty(list)) {
        return
      }
      this.isShowInnerLoading = true
      const params = {
        deviceIndexes: list.map((v, index) => {
          return {
            ...v,
            index: index + 1
          }
        }),
        deviceOrderBy: this.dragType
      }
      const ret = await setDeviceBySchema(params)
      this.isShowInnerLoading = false
      if (this.dragType === 1) {
        this.$message.success('操作成功')
        this.isVisible = false
      }
      console.log(ret)
    },
    async getDeviceBySchema (val) {
      const params = {
        deviceOrderBy: this.dragType,
        schemaId: val.schemaId,
        schemaLevel: val.schemaLevel
      }
      const ret = await getDeviceBySchema(params)

      const member = _.uniq(ret.map(v => v.group)).map(item => {
        return ret.filter(y => y.group === item)
      })
      this.deviceSchemeList = _.cloneDeep(ret)
      this.deviceSchemeListClone = member
      console.log(member)
    },
    getInfo () {
      this.isShowInnerLoading = true
      this.simple = []
      getSchemaOrder().then(res => {
        const ret = [{
          children: res.data,
          schemaId: 1
        }]
        this.simple = _.cloneDeep(ret)
        this.isShowInnerLoading = false
      })
    },
    // 获取车间列表
    getWorkshop () {
      consuming.getOrganize().then(res => {
        this.workshopOptions = res.map(item => {
          return {
            label: item.label,
            value: item.id
          }
        })
        this.workshop = _.get(this.workshopOptions[0], 'value', '')
      })
    },
    // 初始化弹窗
    initDialog () {
      this.isVisible = true
      this.getWorkshop()
    },
    onChangeDragType (val) {
      val === 1 ? this.getWorkshop() : this.getInfo()
    },
    onChangeWorkShop () {
      this.getList()
    },
    getList () {
      this.isShowInnerLoading = true
      getDeviceByWorkshopId(this.workshop).then(res => {
        const ret = res.map((v, index) => {
          return {
            ...v,
            index,
            draggable: true
          }
        })
        this.deviceList = ret
        this.isShowInnerLoading = false
      }).finally(() => {
        this.isShowInnerLoading = false
      })
    },
    submit () {
      const params = _.get(this.simple[0], 'children') || ''
      this.isShowInnerLoading = true
      this.setDeviceBySchema()
      this.dragType === 2 && setSchemaOrder(params).then(res => {
        res.success && this.$message.success('操作成功')
        this.isShowInnerLoading = false
        this.isVisible = false
      }).finally(() => {
        this.$emit('close')
        this.isShowInnerLoading = false
        this.isVisible = false
      })
    }
  }
}
</script>
<style lang="scss">
.ghost {
  opacity: 0.5;
  background: #1890ff;
}

.drag-one{
  width: 48%;
  border: 1px solid #eee;
  border-radius: 10px;
  overflow: hidden;
  &-header{
    height: 48px;
    line-height: 48px;
    color: #fff;
    background: #1890ff;
    font-size: 20px;
    padding-left: 20px;
    font-weight: bold;
  }
  &-main{
    padding: 10px;
    height: 440px;
    overflow: auto;
  }
}

.drag-two{
  width: 48%;
  &-header{
    height: 48px;
    line-height: 48px;
    color: #1890ff;
    font-size: 20px;
    font-weight: bold;
  }
  &-main{
    height: 440px;
    overflow: auto;
    &-item{
      border: 1px solid #eee;
      background: #F2F2F2;
      border-radius: 5px;
      height: 34px;
      line-height: 34px;
      margin-bottom: 5px;
      padding: 0 10px;
      width: 100%;
      overflow: hidden; //超出的文本隐藏
      text-overflow: ellipsis; //溢出用省略号显示
      white-space: nowrap; //溢出不换行
    }
  }
}
.list-group {
  list-style: none;
  color: #222;
  padding: 0 40px;
  max-height: 550px;
  &-item{
    cursor: move;
    height: 36px;
    line-height: 36px;
    border: 1px solid #b6bccb;
    display: flex;
    padding: 0 10px;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
    &:not(:last-child){
      border-bottom: none;
    }
  }
}
</style>
